package com.demo.java.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectUtils {

    /**
     * 调用类的私有方法
     * @param clazz
     * @param constructParams
     * @param methodName
     * @param methodParams
     * @return
     * @throws Exception
     */
    public static Object invokeMethod(Class clazz, Class<?>[] constructParams, String methodName, Object ...methodParams) throws Exception {
        Class<?>[] constructors = constructParams;
        if (constructors == null) {
            constructors = new Class[]{};
        }
        Constructor constructor = clazz.getConstructor(constructors);
        Object instance = constructor.newInstance();

        Class[] methodParamsClazz = new Class[methodParams.length];
        for (int i = 0; i < methodParams.length; i++) {
            methodParamsClazz[i] = methodParams[i].getClass();
        }
        Method method = clazz.getDeclaredMethod(methodName, methodParamsClazz);
        method.setAccessible(true);
        return method.invoke(instance, methodParams);
    }

    /**
     * 调用对象的私有方法
     * @param instance
     * @param methodName
     * @param methodParams
     * @return
     * @throws Exception
     */
    public static Object invokeMethod(Object instance, String methodName, Object ...methodParams) throws Exception {
        Class clazz = instance.getClass();
        Class[] methodParamsClazz = new Class[methodParams.length];
        for (int i = 0; i < methodParams.length; i++) {
            methodParamsClazz[i] = methodParams[i].getClass();
        }
        Method method = clazz.getDeclaredMethod(methodName, methodParamsClazz);
        method.setAccessible(true);
        return method.invoke(instance, methodParams);
    }

    /**
     * 设置对象私有属性
     * @param instance
     * @param fieldName
     * @param value
     * @throws Exception
     */
    public static void setField(Object instance, String fieldName, Object value) throws Exception {
        Field field = instance.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(instance, value);
    }
}
